package com.example.yangyuhua

import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.widget.Button
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.yangyuhua.adapter.StudentAdapter
import com.example.yangyuhua.model.Student
import org.json.JSONArray
import org.json.JSONObject

class MainActivity : ComponentActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var studentAdapter: StudentAdapter
    private val studentList = ArrayList<Student>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        val studentId = "1" // 替换为自己的学号
        val color = getColorByStudentId(studentId)
        setTitleTextColor(color) // 设置标题颜色

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        studentAdapter = StudentAdapter(studentList)
        recyclerView.adapter = studentAdapter

        val button: Button = findViewById(R.id.button)
        button.setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            startActivityForResult(intent, ADD_STUDENT_REQUEST)
        }

        loadStudents() // 加载学生信息
    }

    private fun getColorByStudentId(studentId: String): Int {
        val lastChar = studentId.takeLast(1) // 获取学号的最后一位字符
        return when (lastChar.toString().toIntOrNull()) { // 使用toIntOrNull来避免NumberFormatException
            null, 0, 1 -> android.graphics.Color.RED
            2, 3 -> android.graphics.Color.GREEN
            4, 5 -> android.graphics.Color.BLUE
            6, 7 -> android.graphics.Color.CYAN
            8, 9 -> android.graphics.Color.MAGENTA
            else -> android.graphics.Color.BLACK
        }
    }

    private fun setTitleTextColor(color: Int) {
        val title = this.title
        val spannableString = SpannableString(title)
        spannableString.setSpan(ForegroundColorSpan(color), 0, title.length, 0)
        this.title = spannableString
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ADD_STUDENT_REQUEST && resultCode == RESULT_OK) {
            val student = data?.getSerializableExtra(EXTRA_STUDENT) as Student
            studentList.add(student)
            studentAdapter.notifyDataSetChanged()
            saveStudents() // 保存学生信息
        }
    }

    private fun loadStudents() {
        val sharedPreferences = getSharedPreferences("students", MODE_PRIVATE)
        val studentsJson = sharedPreferences.getString("students", "[]") ?: return
        studentList.clear()
        try {
            val students = JSONArray(studentsJson)
            for (i in 0 until students.length()) {
                val studentJson = students.getJSONObject(i)
                val student = Student(
                    studentJson.getString("studentId"),
                    studentJson.getString("name"),
                    studentJson.getString("gender"),
                    studentJson.getString("className")
                )
                studentList.add(student)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        studentAdapter.notifyDataSetChanged()
    }

    private fun saveStudents() {
        val studentsJson = JSONArray()
        for (student in studentList) {
            val studentJson = JSONObject()
            studentJson.put("studentId", student.studentId)
            studentJson.put("name", student.name)
            studentJson.put("gender", student.gender)
            studentJson.put("className", student.className)
            studentsJson.put(studentJson)
        }
        val sharedPreferences = getSharedPreferences("students", MODE_PRIVATE)
        with (sharedPreferences.edit()) {
            putString("students", studentsJson.toString())
            apply()
        }
    }

    companion object {
        const val ADD_STUDENT_REQUEST = 1
        const val EXTRA_STUDENT = "EXTRA_STUDENT"
    }
}
